package jdbc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author Yancy
 * @program springioctest
 * @create 2021-01-24
 */
public class DbUtil {

    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {
            readConfig();
            Class.forName(driverClass);
            con = DriverManager.getConnection(url, username, password);
        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
        return con;
    }

    /**
     * 获取配置文件中的数据库信息
     */
    public static void readConfig() throws IOException {
        InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties pro = new Properties();
        pro.load(in);
        driverClass = pro.getProperty("driverClass");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
    }

    /**
     * DML操作
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql ,Object[] params){
        Connection connection = null;
        PreparedStatement psm = null;
        int n = 0;
        try {
            connection = getConnection();
            psm = connection.prepareStatement(sql);
            for (int i = 0;i<params.length;i++){
                psm.setObject(i+1,params[i]);
            }
            n = psm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return n;
    }



    /**
     * 关闭资源
     */
    public static void close(Connection con,Statement sm ,ResultSet rs){
        try{
            if (rs!=null){
                rs.close();
            }
            if (sm!=null){
                sm.close();
            }
            if (con!=null){
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
